
/*
 * BanBu_PersonAlbumDetailController
 * @description 本文件提供个人空间界面的相册展示部分
 * @package
 * @author 		yinlinlin
 * @copyright
 * @version 		1.0
 * @description 本文件提供个人空间界面的相册展示部分
 */

#import "BanBu_PersonAlbumDetailController.h"
#import "AppCommunicationManager.h"
#import "TKLoadingView.h"
#import "AppDataManager.h"
#import "BanBu_PhotoShowViewController.h"
#import "SDNCreateAlbumsViewController.h"
#import "BanBu_AlbumPreviewCell.h"
#import "BanBu_ImageView.h"
#import "BanBu_PersonAlbumCell.h"
@interface BanBu_PersonAlbumDetailController ()
{
    UIView * headerV;
}
@end

@implementation BanBu_PersonAlbumDetailController
@synthesize delegate = _delegate;
@synthesize user_id = _user_id;
@synthesize albumType = _albumType;
@synthesize refreStr = _refreStr;
- (void)dealloc
{
    self.albumType = nil;
    [_user_id release];
    _user_id = nil;
    [_photoAlbumArr release];
    _photoAlbumArr = nil;
    [_albumType release];
    if (_albumType)
    {
        _albumType = nil;
        self.delegate = nil;
    }
    [headerV release];
    headerV = nil;
    [_refreStr release];
    _refreStr = nil;
    _createBu = nil;
    _previewBu = nil;
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
    //    if (([_albumType isEqualToString:album_Type]) && ([_user_id isEqualToString:MyAppDataManager.useruid]))
    //    {
    ////        [self getPhotoAlbumList];
    //    }
    
    if (([_albumType isEqualToString:album_Type]) && ([_refreStr isEqualToString:album_refresh]))
    {
        [_refreStr setString:@""];
        [_refreStr appendString:@"refreshNo"];
        [self getPhotoAlbumList];
    }
    [super viewWillAppear:animated ];
}
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([_albumType isEqualToString:album_Type])
    {
        [self getPhotoAlbumList];
    }
    
    //初始化刷新标志字符串
    _refreStr = [[NSMutableString alloc]initWithCapacity:10];
    [_refreStr appendString:@"refreshNo"];
    
    if ([_albumType isEqualToString:album_Type])
    {
        self.title = NSLocalizedString(@"myalbumTitle", 我的相册);
    }
    self.view.backgroundColor = [UIColor clearColor];
    self.tableView.backgroundView = nil;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.separatorColor = [UIColor clearColor];
    //2014年09月28日17:45:08 by yinlinlin 修改个人空间下方的3个按钮
    UIView * footerV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    footerV.backgroundColor = [UIColor clearColor];
    self.tableView.tableFooterView = footerV;
    [footerV release];
    //修改完成

    
    BanBu_ImageView *backImage = [[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable];
    self.tableView.backgroundView = backImage;
    [backImage release];
    
    _photoAlbumArr = [[NSMutableArray alloc]initWithCapacity:30];
    if ([self.user_id isEqualToString:MyAppDataManager.useruid])
    {
        _person_Tag = PERSON_MYSELF;
    }
    else
    {
        _person_Tag = PERSON_OTHERS;
    }
    //创建相册按钮
    _createBu = [UIButton buttonWithType:UIButtonTypeCustom];
    [_createBu setFrame:CGRectMake(15.5, 10, 137, 34)];
    [_createBu setBackgroundImage:[[UIImage imageNamed:@"manage_selected.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 40, 10, 40)] forState:UIControlStateNormal];
    
    [_createBu setTitle:NSLocalizedString(@"album_create1", 创建相册) forState:UIControlStateNormal];
    [_createBu addTarget:self action:@selector(createPhotoAlbumPressed) forControlEvents:UIControlEventTouchUpInside];
    
    //预览相册按钮
    _previewBu = [UIButton buttonWithType:UIButtonTypeCustom];
    [_previewBu setFrame:CGRectMake(168.5, 10, 137, 34)];
    [_previewBu setBackgroundImage:[[UIImage imageNamed:@"manage_selected.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 40, 10, 40)] forState:UIControlStateNormal];
    
    [_previewBu setTitle:NSLocalizedString(@"album_preview", 预览相册) forState:UIControlStateNormal];
    [_previewBu setTitle:NSLocalizedString(@"album_normal", nil) forState:UIControlStateSelected];
    [_previewBu addTarget:self action:@selector(managePhotoAlbumPressed) forControlEvents:UIControlEventTouchUpInside];
    headerV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 60)];
    headerV.backgroundColor = UIColorWithRGB(255, 255, 255, 0.4);
    [headerV addSubview:_createBu];
    [headerV addSubview:_previewBu];
    
}
#pragma mark - 获取相册列表
/**
 * @函数名称：getPhotoAlbumList
 * @函数描述：获取用户所有相册列表
 * @输入参数：void
 * @输出参数：获取用户所有相册列表
 * @返回值：void
 */
-(void)getPhotoAlbumList
{
    [_photoAlbumArr removeAllObjects];
    [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"loadingNotice", nil) activityAnimated:YES];
    NSDictionary *parDic = [NSDictionary dictionaryWithObjectsAndKeys:self.user_id,@"userid",nil];
    
    //    [MyAppDataManager showTime:@"开始加载相册"];
    [AppComManager getBanBuAlbumData:BanBu_v2_Get_Albumlist_Byuser par:parDic delegate:self];
    //    for (int i = 0; i < 10; i ++)
    //    {
    //        [MyAppDataManager showTime:@"开始加载相册"];
    //        [AppComManager getBanBuData:BanBu_v2_Get_Albumlist_Byuser par:parDic delegate:self];
    //
    //    }
}

#pragma  mark - banbuRequestDidFinished
- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    
    NSLog(@"%@",resDic);
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:NO afterShow:0];
    [TKLoadingView dismissTkFromView:self.view animated:NO afterShow:0];
    if(error)
    {
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:1];
        
    }
    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_v2_Get_Albumlist_Byuser])
    {
        //        NSLog(@"%@",resDic);
        if([[resDic valueForKey:@"ok"] boolValue])
        {
            NSArray *albumList = [resDic objectForKey:@"albumlist"];
            NSLog(@"%@",albumList);
            [_photoAlbumArr removeAllObjects];
            for (NSDictionary * albumDict in albumList)
            {
                NSLog(@"test:%@",albumDict);
                BanBu_AlbumModel * album_model = [[BanBu_AlbumModel alloc]init];
                album_model.image_url = nil;
                album_model.album_id = [albumDict valueForKey:@"albumid"];
                NSDictionary * content = [albumDict valueForKey:@"content"];
                //系统相册
                if ([[albumDict valueForKey:@"is_sys"] boolValue])
                {
                    album_model.album_title = [MyAppDataManager IsInternationalLanguage:[albumDict valueForKey:@"albumname"]];
                    //NSLocalizedString([albumDict valueForKey:@"albumname"], 系统相册名称);
                    NSLog(@"%@",album_model.album_title);
                    album_model.album_type = ALBUM_SYSTEM;
                }
                else//用户自定义相册
                {
                    album_model.album_title = [albumDict valueForKey:@"albumname"];
                    album_model.album_type = ALBUM_PERSONAL;
                    
                    if ([content isKindOfClass:[NSDictionary class]])
                    {
                        NSLog(@"%d",[[content valueForKey:@"stringof"] integerValue]);
                        album_model.personalbum_type = [[content valueForKey:@"stringof"] integerValue];
                        album_model.question = [content valueForKey:@"byquestion"];
                        album_model.answer = [content valueForKey:@"answerof"];
                        album_model.opengroup = [content valueForKey:@"opengroup"];
                        album_model.hidegroup = [content valueForKey:@"hidegroup"];
                    }
                    
                    
                }
                if ([content isKindOfClass:[NSDictionary class]])
                {
                    album_model.image_url = [content valueForKey:@"facefile"];
                    
                    album_model.faceIdStr = [content valueForKey:@"facejoin"];
                }
                
                album_model.user_id = self.user_id;
                album_model.numCount = [[albumDict valueForKey:@"countof"] integerValue];
                [_photoAlbumArr addObject:album_model];
                [album_model release];
            }
            [self.tableView reloadData];
        }
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        //验证回答的问题
        UITextField *field = [alertView textFieldAtIndex:0];
        BanBu_AlbumModel * album_model = [_photoAlbumArr objectAtIndex:alertView.tag - 100];
        if ([field.text isEqualToString:album_model.answer])
        {
            BanBu_PhotoShowViewController * photoShow = [[BanBu_PhotoShowViewController alloc]init];
            photoShow.albumModel = album_model;
            if ([_albumType isEqualToString:album_Type])
            {
                [self.navigationController pushViewController:photoShow animated:YES];
                [photoShow release];
                photoShow = nil;
                
            }
            else
            {
                UIViewController * nv = (UIViewController *)_delegate;
                [nv.navigationController pushViewController:photoShow animated:YES];
                [photoShow release];
                photoShow = nil;
                
            }
        }
        else
        {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"noticeNotice", nil) message:NSLocalizedString(@"album_noAnswer", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"confirmNotice", nil) otherButtonTitles: nil];
            [alert show];
        }
    }
}

#pragma mark - 点击创建相册按钮

- (void)createPhotoAlbumPressed
{
    //    BanBu_CreateAlbumViewController * createV = [[BanBu_CreateAlbumViewController alloc]init];
    //    UIViewController * nv = (UIViewController *)_delegate;
    //    [nv.navigationController pushViewController:createV animated:YES];
    //    [createV release];
    
    SDNCreateAlbumsViewController *nestedNav = [[SDNCreateAlbumsViewController alloc] init];
    __block BanBu_PersonAlbumDetailController * bself = self;
    __block NSMutableArray * bphotoArr =_photoAlbumArr;
    
    //创建相册成功，重新请求数据
    [nestedNav setCreateSuccessCallBack:^(BanBu_AlbumModel * album_Model){
        //        [bself getPhotoAlbumList];
        //将新创建的相册加入到相册列表中第一位
        [bphotoArr insertObject:album_Model atIndex:0];
        [bself.tableView reloadData];
        [bself performSelector:@selector(passToDatailAlbum:) withObject:album_Model afterDelay:1.0];
    }];
    if ([_albumType isEqualToString:album_Type])
    {
        [self.navigationController pushViewController:nestedNav animated:YES];
    }
    else
    {
        UIViewController * nv = (UIViewController *)_delegate;
        [nv.navigationController pushViewController:nestedNav animated:YES];
    }
    [nestedNav release];
    nestedNav = nil;
    
}
#pragma mark - 点击管理相册按钮
- (void)managePhotoAlbumPressed
{
    //预览相册
    if (_person_Tag == PERSON_PREVIEW)
    {
        [_previewBu setSelected:NO];
        _person_Tag = PERSON_MYSELF;
        
    }
    else
    {
        [_previewBu setSelected:YES];
        _person_Tag = PERSON_PREVIEW;
    }
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_person_Tag == PERSON_MYSELF)
    {
        NSInteger addNum = 0;
        if (_photoAlbumArr.count % 3 > 0)
        {
            addNum = 1;
        }
        return _photoAlbumArr.count / 3 + addNum;
        
    }
    else
    {
        return _photoAlbumArr.count;
    }
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_person_Tag == PERSON_MYSELF)
    {
        return 120;
    }
    return 310;
}

- (void)passToDatailAlbum:(BanBu_AlbumModel *)album_model
{
    BanBu_PhotoShowViewController * photoShow = [[BanBu_PhotoShowViewController alloc]init];
    photoShow.albumModel = album_model;
    __block BanBu_PersonAlbumDetailController * bself = self;
    //    __block NSMutableArray * bphotoAlbumArr = _photoAlbumArr;
    __block BanBu_AlbumModel * balbum_model = album_model;
    __block NSMutableArray * bphotoAlbumArr = _photoAlbumArr;
    //在相册编辑界面重新设置封面
    __block NSMutableString * brefreStr = _refreStr;
    [photoShow setSetCoverCallBack:^(NSString *newCoverpath)
     {
         
//         [brefreStr setString:@""];
//         [brefreStr appendString:album_refresh];
         balbum_model.image_url = newCoverpath;
         [bself.tableView reloadData];
     }];
    //移除被删除的相册
    [photoShow setDeleteAlbumCallBack:^{
        [bphotoAlbumArr removeObject:album_model];
        [bself.tableView reloadData];
        //        [bself getPhotoAlbumList];
    }];
    
    //修改相册属性的回调
    [photoShow setChangeAlbumCallBack:^(BanBu_AlbumModel *change_model) {
        balbum_model.album_title = change_model.album_title;
        balbum_model.personalbum_type = change_model.personalbum_type;
        balbum_model.opengroup = change_model.opengroup;
        balbum_model.hidegroup = change_model.hidegroup;
        balbum_model.question = change_model.question;
        balbum_model.answer = change_model.answer;
        [bself.tableView reloadData];
        
    }];
//    __block NSMutableString * brefreStr = _refreStr;
    [photoShow setRefreshDataCallBack:^{
        [brefreStr setString:@""];
        [brefreStr appendString:album_refresh];
    }];
    
    if ([_albumType isEqualToString:album_Type])
    {
        [self.navigationController pushViewController:photoShow animated:YES];
        [photoShow release];
        photoShow = nil;
        
    }
    else
    {
        UIViewController * nv = (UIViewController *)_delegate;
        [nv.navigationController pushViewController:photoShow animated:YES];
        [photoShow release];
        photoShow = nil;
        
    }
    
    
}

- (void)passToAlbumDetailView:(NSInteger)tag andArr:(NSArray*)barray
{
    BanBu_AlbumModel * album_model = [barray objectAtIndex:tag];
    [self passToDatailAlbum:album_model];
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_person_Tag == PERSON_MYSELF)
    {
        static NSString * cellFlag1 = @"cellFlag1";
        BanBu_PersonAlbumCell * cell = (BanBu_PersonAlbumCell *)[tableView dequeueReusableCellWithIdentifier:cellFlag1];
        if (!cell)
        {
            cell = [[[BanBu_PersonAlbumCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellFlag1]autorelease];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor clearColor];
        }
        //剩余未排版照片数量
        NSInteger end = _photoAlbumArr.count - indexPath.row * 3;
        end = (end >= 3)?3:end;
        NSLog(@"%d",end);
        
        NSMutableArray * array = [[[NSMutableArray alloc]initWithCapacity:3]autorelease];
        for (int i = 0; i < end; i++)
        {
            BanBu_MediaModel * mediaModel = [_photoAlbumArr objectAtIndex:i + indexPath.row * 3];
            [array addObject:mediaModel];
        }
        [cell updatePersonAlbumCellData:array];
        __block id bself = self;
        [cell setSingleTapOnAlbumCallBack:^(NSInteger tag, NSArray * barray)
         {
             [bself passToAlbumDetailView:tag andArr:barray];
         }];
        return cell;
        
    }
    else
    {
        static NSString * cellFlag0 = @"cellFlag0";
        BanBu_AlbumPreviewCell * cell = (BanBu_AlbumPreviewCell *)[tableView dequeueReusableCellWithIdentifier:cellFlag0];
        if (!cell)
        {
            cell = [[[BanBu_AlbumPreviewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellFlag0]autorelease];
        }
        [cell updateCellData:[_photoAlbumArr objectAtIndex:indexPath.row]];
        
        return cell;
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if ((_person_Tag == PERSON_MYSELF) || (_person_Tag == PERSON_PREVIEW))
    {
        if (section == 0)
        {
            return headerV;
        }
        return nil;
        
    }
    return nil;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if ((_person_Tag == PERSON_MYSELF) || (_person_Tag == PERSON_PREVIEW))
    {
        if (section == 0)
        {
            return 54;
        }
        return 0.0f;
        
    }
    
    return 0.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!(_person_Tag == PERSON_MYSELF))
    {
        BanBu_AlbumModel * album_model = [_photoAlbumArr objectAtIndex:indexPath.row];
        //回答问题可见相册
        if ((album_model.personalbum_type == CREATE_QUESSTION) && (![album_model.user_id isEqualToString:MyAppDataManager.useruid]))
        {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"Competence_qs", 回答问题) message:album_model.question delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", 取消) otherButtonTitles:NSLocalizedString(@"confirmNotice", 确定),nil];
            alert.tag = indexPath.row + 100;
            alert.alertViewStyle = UIAlertViewStylePlainTextInput;
            [alert show];
            return;
        }
        [self passToDatailAlbum:album_model];
        return;
    }
}
/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
